package com.nf.nf.util;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {
		public static String getClinetIpByReq(HttpServletRequest request) {
			String clientIp = request.getHeader("x-forwarded-for");

			if ((clientIp == null) || (clientIp.length() == 0)
					|| ("unknown".equalsIgnoreCase(clientIp))) {
				clientIp = request.getHeader("Proxy-Client-IP");
			}
			if ((clientIp == null) || (clientIp.length() == 0)
					|| ("unknown".equalsIgnoreCase(clientIp))) {
				clientIp = request.getHeader("WL-Proxy-Client-IP");
			}
			if ((clientIp == null) || (clientIp.length() == 0)
					|| ("unknown".equalsIgnoreCase(clientIp))) {
				clientIp = request.getRemoteAddr();
			}

			String sIP = null;
			if ((clientIp != null) && (clientIp.indexOf("unknown") == -1)
					&& (clientIp.indexOf(",") > 0)) {
				String[] ipsz = clientIp.split(",");
				for (int i = 0; i < ipsz.length; i++) {
					if (!isInnerIP(ipsz[i].trim())) {
						sIP = ipsz[i].trim();
						break;
					}

				}

				if (sIP == null) {
					sIP = ipsz[0].trim();
				}
				clientIp = sIP;
			}
			if ((clientIp != null) && (clientIp.indexOf("unknown") != -1)) {
				clientIp = clientIp.replaceAll("unknown,", "");
				clientIp = clientIp.trim();
			}

			if (("".equals(clientIp)) || (clientIp == null)) {
				clientIp = "127.0.0.1";
			}
			return clientIp;
		}

		private static boolean isInner(long userIp, long begin, long end) {
			boolean isInner = (userIp >= begin) && (userIp <= end);

			return isInner;
		}

		public static boolean isInnerIP(String ipAddress) {
			boolean isInnerIp = false;

			long ipNum = getIpNum(ipAddress);

			long aBegin = getIpNum("10.0.0.0");
			long aEnd = getIpNum("10.255.255.255");

			long bBegin = getIpNum("172.16.0.0");
			long bEnd = getIpNum("172.31.255.255");

			long cBegin = getIpNum("192.168.0.0");
			long cEnd = getIpNum("192.168.255.255");
			isInnerIp = (isInner(ipNum, aBegin, aEnd))
					|| (isInner(ipNum, bBegin, bEnd))
					|| (isInner(ipNum, cBegin, cEnd))
					|| (ipAddress.equals("127.0.0.1"));

			return isInnerIp;
		}

		private static long getIpNum(String ipAddress) {
			String[] ip = ipAddress.split("\\.");
			long a = Integer.parseInt(ip[0]);
			long b = Integer.parseInt(ip[1]);
			long c = Integer.parseInt(ip[2]);
			long d = Integer.parseInt(ip[3]);

			long ipNum = a * 256L * 256L * 256L + b * 256L * 256L + c * 256L + d;
			return ipNum;
		}
}
